package com.qtjf.qtmoneyservice.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qtjf.qtmoneyservice.MyApplication;
import com.qtjf.qtmoneyservice.R;
import com.qtjf.qtmoneyservice.constantSet.Constant;
import com.qtjf.qtmoneyservice.domain.Banner;
import com.qtjf.qtmoneyservice.domain.RegisterState;
import com.qtjf.qtmoneyservice.domain.ResultBanner;
import com.qtjf.qtmoneyservice.domain.ResultProduct;
import com.qtjf.qtmoneyservice.domain.SimpleResult;
import com.qtjf.qtmoneyservice.domain.Token;
import com.qtjf.qtmoneyservice.utils.FirstTip;
import com.qtjf.qtmoneyservice.utils.RequestNetApi;
import com.qtjf.qtmoneyservice.view.HomeRecyclerHeadView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import impl.IHttpListener;

public class LoginActivity extends BaseActivity {
    ImageView mBack;
    EditText phoneText;
    TextView sendBt;
    TextView startBt;
    EditText codeText;
    int i=60;
    Token token;
    Gson gson;
    RegisterState registerState;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        super.setTranslucent();

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mBack= (ImageView) findViewById(R.id.back_bt);
        phoneText= (EditText) findViewById(R.id.phone_text);
        sendBt= (TextView) findViewById(R.id.send_bt);
        sendBt.setClickable(false);
        startBt= (TextView) findViewById(R.id.start_bt);
        codeText= (EditText) findViewById(R.id.code_text);
    }

    private void initData() {
        gson=new Gson();
    }

    private void initEvent() {
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginActivity.this.finish();
            }
        });


        phoneText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.length()==11)
                {
                    sendBt.setClickable(true);
                    sendBt.setTextColor(Color.parseColor("#4162ff"));
                }else
                {
                    sendBt.setClickable(false);
                    sendBt.setTextColor(Color.parseColor("#999999"));
                }
            }
        });

        sendBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(phoneText.getText().toString().trim().length()==11) {
                    i = 60;
                    requestCall();
                    sendBt.setClickable(false);
                    sendBt.setTextColor(Color.parseColor("#999999"));
                    new Thread(
                            new Runnable() {
                                @Override
                                public void run() {
                                    while (i >= 0) {
                                        try {
                                            Thread.sleep(1000);
                                            i--;
                                            sendBt.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (i < 0) {
                                                        sendBt.setText("发送验证码");
                                                        if (phoneText.getText().toString().trim().length() == 11) {
                                                            sendBt.setClickable(true);
                                                            sendBt.setTextColor(Color.parseColor("#4162ff"));
                                                        }
                                                    } else {
                                                        sendBt.setText(i + "s后重试");
                                                    }

                                                }
                                            });
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                    ).start();
                }
            }
        });

        startBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getToken();
                if(registerState!=null) {
                    if (registerState.getData() == null||registerState.getData().equals("")) {
                        register();
                    } else {
                        login();
                    }
                }else{
                    Toast.makeText(LoginActivity.this, "请先获取验证码", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void requestCall() {
        String url= Constant.HOMEADDRESS + "index/sendSmsCode?usermobile="+phoneText.getText().toString().trim()+"&type=app";
        final StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub
                Log.d("999",response);
                registerState = gson.fromJson(response, new TypeToken<RegisterState>() {
                }.getType());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                Toast.makeText(LoginActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
            }

        }) {
            // 需要重写获取参数的函数,可以向服务器提交参数
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                return map;
            }

        };


        MyApplication.getQueue().add(stringRequest);

    }

    private void login()
    {
        //http://118.89.185.176:8082/index/login?usermobile=15258888888&type=app&authCode=888888
        String url= Constant.HOMEADDRESS + "index/login?usermobile="+phoneText.getText().toString()+"&type=app&authCode="+codeText.getText().toString();
        final StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub

                Log.d("999",response);
                if(response.length()>10) {
                    SimpleResult simpleResult = gson.fromJson(response, new TypeToken<SimpleResult>() {
                    }.getType());

                    if(simpleResult.getStatus().trim().equals("200"))
                    {
                        FirstTip firstTip=new FirstTip(LoginActivity.this,"loginFile");
                        firstTip.saveVipLevel("loginKey",phoneText.getText().toString().trim());
                        startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                        LoginActivity.this.finish();
                        Constant.setUsermobile(phoneText.getText().toString().trim());

                        FirstTip firstAn=new FirstTip(LoginActivity.this,"FirstAnzhuang");
                        firstAn.saveVipLevel("tipKey","1");
                    }else {
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                Toast.makeText(LoginActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
            }

        }) {
            // 需要重写获取参数的函数,可以向服务器提交参数
           /* protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobile",phoneText.getText().toString());
                map.put("captcha",codeText.getText().toString());
                return map;
            }*/

        };


        MyApplication.getQueue().add(stringRequest);

    }




    private void register()
    {
        //http://118.89.185.176:8082/index/register?usermobile=15258888888&type=app&authCode=888888&invite=15255555555
        String url= Constant.HOMEADDRESS + "index/register?usermobile="+phoneText.getText().toString()+"&type=app&authCode="+codeText.getText().toString();
        final StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // TODO Auto-generated method stub
                Log.d("999","zhuce"+response);
                if(response.length()>10) {
                    SimpleResult simpleResult = gson.fromJson(response, new TypeToken<SimpleResult>() {
                    }.getType());

                    if(simpleResult.getStatus().trim().equals("200"))
                    {

                        FirstTip firstAn=new FirstTip(LoginActivity.this,"FirstAnzhuang");
                        firstAn.saveVipLevel("tipKey","1");

                        FirstTip firstTip=new FirstTip(LoginActivity.this,"loginFile");
                        firstTip.saveVipLevel("loginKey",phoneText.getText().toString().trim());
                        startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                        LoginActivity.this.finish();
                        Constant.setUsermobile(phoneText.getText().toString().trim());
                    }else {
                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                Toast.makeText(LoginActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
            }

        }) {
            // 需要重写获取参数的函数,可以向服务器提交参数
           /* protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("mobile",phoneText.getText().toString());
                map.put("captcha",codeText.getText().toString());
                return map;
            }*/

        };


        MyApplication.getQueue().add(stringRequest);

    }

}
